import { getCartList, changeCount, delSelect } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    // 提供一个方法设置CartList
    setCartList (state, newValue) {
      state.cartList = newValue
    },
    // 单选商品
    toggleCheck (state, goodsId) {
      // 让对应的id取反
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, flag) {
      // 所有小选框同步
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    // 本地修改数量
    changeCount (state, { goodsId, value }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = value
    }
  },
  actions: {
    async getCartAction (context) {
      const { data } = await getCartList()
      // 后台返回的数据中不包含复选框的状态，
      // 为了实现功能 需要手动维护数据，给每一项添加一个isChecked状态（标记当前商品是否选中）
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsId, value, skuId } = obj
      // 1.本地修改
      context.commit('changeCount', { goodsId, value })
      // 2.同步后台
      await changeCount(goodsId, value, skuId)
      // console.log(res)
    },
    // 删除购物车数据
    async delSelect (context) {
      const selCartList = context.getters.selCartList
      const cartIds = selCartList.map(item => item.id)
      // console.log(cartIds)
      await delSelect(cartIds)
      Toast('删除成功')
      // 删除成功后 重新渲染
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 商品总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的商品
    selCartList (state) {
      return state.cartList.filter((item) => item.isChecked)
    },
    // 选中的总数
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的总价
    selPrice (state, getters) {
      return getters.selCartList.reduce((num, item) => num + (item.goods_num * item.goods.goods_price_min), 0).toFixed(2)
    },
    // 全选
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
